package com.jiangnanxiaoguan.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiangnanxiaoguan.common.BaseContext;
import com.jiangnanxiaoguan.common.Result;
import com.jiangnanxiaoguan.dto.OrdersDto;
import com.jiangnanxiaoguan.entity.OrderDetail;
import com.jiangnanxiaoguan.entity.Orders;
import com.jiangnanxiaoguan.service.OrderDetailService;
import com.jiangnanxiaoguan.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author 不愿透露姓名的狂热者
 * @since 2022-09-11
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单。
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public Result<String> submit(@RequestBody Orders orders) {
        log.info("订单信息：{}", orders);
        ordersService.submit(orders);
        return Result.success("");
    }

    /**
     * 用户端历史订单分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public Result<IPage<OrdersDto>> orderList(Integer page, Integer pageSize) {
        log.info("[用户端历史订单分页查询] 查询页码：{}, 查询页码大小：{}", page, pageSize);

        // 用户id（查询条件）
        Long userId = BaseContext.getCurrentId();

        // 分页查询条件对象构造
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId, userId);

        // 分页信息
        IPage<Orders> ordersPage = new Page<>(page, pageSize);

        // 分页查询
        ordersService.page(ordersPage, ordersLambdaQueryWrapper);

        // 全部订单
        List<Orders> ordersList = ordersPage.getRecords();

        if (ordersList.isEmpty()) {
            return Result.success(null);
        }

        // 得到全部订单id
        List<Long> orderIdList = ordersList.stream().map(Orders::getId).collect(Collectors.toList());
        // 构造批量查询条件（in）
        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderDetailLambdaQueryWrapper.in(OrderDetail::getOrderId, orderIdList);
        // 批量查询订单明细
        List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);


        // 使用dto追加订单明细返回给前端使用
        Page<OrdersDto> ordersDtoPage = new Page<>();
        // 得到全部订单包括对应的订单明细
        List<OrdersDto> ordersDtoList = ordersList.stream().map(order -> {
            // 1.先查询出该订单所有明细
            List<OrderDetail> orderDetails = orderDetailList.stream()
                    .filter(orderDetail -> order.getId().equals(orderDetail.getOrderId()))
                    .collect(Collectors.toList());

            // 2.追加商品数量到订单
            int itemNumbers = 0;
            for (OrderDetail orderDetail : orderDetails) {
                itemNumbers += orderDetail.getNumber();
            }
            order.setSumNum(itemNumbers);

            // 3.订单的扩展实体类(Data Transfer Object)
            OrdersDto orderDto = new OrdersDto();
            // 将订单的基本信息拷贝到dto(订单基本信息中已经拥有了商品数量信息)
            BeanUtils.copyProperties(order, orderDto);

            // 4.再将订单明细追加到dto
            orderDto.setOrderDetails(orderDetails);

            return orderDto;
        }).collect(Collectors.toList());
        // 追加订单明细到分页对象
        ordersDtoPage.setRecords(ordersDtoList);
//        Map<Long, Integer> itemNumbersMap = new HashMap<>();
//        for (Long id : orderIdList) {
//            // 过滤出该订单对应所有订单明细
//            List<OrderDetail> orderDetails = orderDetailList.stream()
//                    .filter(orderDetail -> id.equals(orderDetail.getOrderId())).collect(Collectors.toList());
//            // 遍历该订单的明细，求出该订单商品数量。
//            int itemNumbers = 0;
//            for (OrderDetail orderDetail : orderDetails) {
//                itemNumbers += orderDetail.getNumber();
//            }
//            itemNumbersMap.put(id, itemNumbers);
//        }

        // 取到全部订单号和订单商品数量
//        HashMap<Long, Integer> itemNumbersMap = new HashMap<>();
//        for (Long id : orderIdList) {
//            Integer itemNumbers = 0;
//            for (OrderDetail orderDetail : orderDetailList) {
//                if (id.equals(orderDetail.getOrderId())) {
//                    itemNumbers += orderDetail.getNumber();
//                }
//            }
//            itemNumbersMap.put(id, itemNumbers);
//        }

        // 给每个订单追加商品数量
//        for (Orders orders : ordersList) {
//            Integer itemNumbers = itemNumbersMap.get(orders.getId());
//            orders.setSumNum(itemNumbers);
//        }

        // 更新一下订单集合
//        ordersPage.setRecords(ordersList);
        return Result.success(ordersDtoPage);
    }

    /**
     *  管理端订单明细。
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result<IPage<Orders>> page(Integer page, Integer pageSize, Long number, String beginTime, String endTime) {
        log.info("[管理端订单明细分页查询] 当前页码：{}, 当前页码大小：{}", page, pageSize);
        log.info("订单号：{}", number);
        log.info("开始时间：{}, 结束时间：{}", beginTime, endTime);

        // 构造查询条件
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
                                // 订单号
        ordersLambdaQueryWrapper.eq(number != null, Orders::getNumber, number)
                                // 时间范围
                                .between(StringUtils.isNotEmpty(beginTime) && StringUtils.isNotEmpty(endTime),
                                        Orders::getOrderTime, beginTime, endTime);
        // 查询
        IPage<Orders> ordersPage = new Page<>(page, pageSize);
        ordersService.page(ordersPage, ordersLambdaQueryWrapper);

        return Result.success(ordersPage);
    }

    /**
     * 通用修改订单（状态：已派送/完成）。
     * @param orders
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody Orders orders) {
        log.info("订单信息：{}", orders);
        ordersService.updateById(orders);
        return Result.success("");
    }

    /**
     * 再来一单，其实就是回主页而已。
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public Result<String> again(@RequestBody Orders orders) {
        log.info("订单id：{}", orders.getId());
        return Result.success("");
    }
}

